package service

import (
	"advertising/config/redis"
	"advertising/internal/define"
	"advertising/internal/pkg/thirdapi"
	"context"
	"strconv"
	"strings"
	"time"

	"192.168.1.75/go-pkg/helper"
	"github.com/golang-module/carbon"
)

type ThirdApi struct{}

// 获取广告列表
// RobotID: DDRetail158_1 需转为 DDRetail158_97
func (ThirdApi) YiShouAdvertisingList(ctx context.Context, RobotID string) (res []thirdapi.YiShouSubscribeRspPayload, err error) {
	if strings.HasSuffix(RobotID, "_1") {
		RobotID = strings.Replace(RobotID, "_1", "_97", 1)
	} else if strings.HasSuffix(RobotID, "_2") {
		RobotID = strings.Replace(RobotID, "_2", "_98", 1)
	}
	rdb := redis.NewDB()
	yishouAPI := thirdapi.NewYiShou()
	res = []thirdapi.YiShouSubscribeRspPayload{}
	// 获取设备广告位
	slotList, slotErr := yishouAPI.DeviceSlotInfo(ctx, RobotID)
	if slotErr == nil && len(slotList) > 0 {
		heart, _ := rdb.Get(context.Background(), define.RedisYiShouDeviceHeartPrefix+RobotID).Result()
		if heart == "" {
			var slots []thirdapi.YiShouHeartSlot
			for _, slot := range slotList {
				slots = append(slots, thirdapi.YiShouHeartSlot{SlotID: slot.SlotID})
			}
			// 心跳
			heartRes, err := yishouAPI.Heart(ctx, RobotID, "", "", 0, 0, slots)
			if err == nil {
				// 存储心跳
				expire := carbon.Now().DiffInSeconds(carbon.ParseByLayout(heartRes.NextTime, carbon.DateTimeLayout))
				if expire > 0 {
					rdb.Set(context.Background(), define.RedisYiShouDeviceHeartPrefix+RobotID, 1, time.Duration(expire)*time.Second)
				}
			}
		}
		// 广告订阅
		for _, slot := range slotList {
			slotID := strconv.FormatInt(slot.SlotID, 10)
			subscribeRes, subscribeErr := yishouAPI.Subscribe(ctx, RobotID, slotID)
			if subscribeErr != nil {
				err = subscribeErr
				return
			}
			for k, v := range subscribeRes {
				subscribeRes[k].ID, _ = helper.UUID{}.String()
				subscribeRes[k].ID = "yishou" + subscribeRes[k].ID
				// 广告点击链接存储，用于触发广告点击反馈
				rdb.Set(context.Background(), define.RedisYiShouTrackPrefix+subscribeRes[k].ID, v.TrackUrl, time.Minute*30)
			}
			res = append(res, subscribeRes...)
		}
	}

	return
}
